import { useState } from 'react'
import {
  type ColumnFiltersState,
  type RowData,
  type SortingState,
  type VisibilityState,
  flexRender,
  getCoreRowModel,
  getFacetedRowModel,
  getFacetedUniqueValues,
  getFilteredRowModel,
  getPaginationRowModel,
  getSortedRowModel,
  useReactTable,
  PaginationState
} from '@tanstack/react-table'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import { type User } from '../data/schema'
import { DataTablePagination } from './data-table-pagination'
import { DataTableToolbar } from './data-table-toolbar'
import { columns } from './users-columns'
import { useQuery } from '@tanstack/react-query'
import { userKeys, users } from '@/api/users'

declare module '@tanstack/react-table' {
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  interface ColumnMeta<TData extends RowData, TValue> {
    className: string
  }
}

export function UsersTable() {
  // 行选择状态，类型为 Record<string, boolean>，键为行ID，值为是否选中
  const [rowSelection, setRowSelection] = useState({})
  const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({})
  const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>([])
  const [sorting, setSorting] = useState<SortingState>([])

  const [pagination, setPagination] = useState<PaginationState>({
    pageIndex: 0,
    pageSize: 10,
  })

  // 使用 useQuery hook 获取数据，并处理加载状态和错误
  const {
    data: usersData,
    isLoading,
    isError,
    error,
    refetch
  } = useQuery({
    queryKey: [...userKeys.all(), pagination.pageIndex, pagination.pageSize],
    queryFn: async () => {
      return await users({
        page: pagination.pageIndex + 1,
        limit: pagination.pageSize
      });

    },
    staleTime: 5 * 60 * 1000, // 5分钟内数据不会被标记为过期
    retry: 1, // 自动重试一次
    retryDelay: 1000, // 重试延迟1秒
  })

  // 用户数据获取完成
  const data: User[] = usersData?.data?.data || []
  const rowCount = usersData?.data?.count || 0

  // 使用 useMemo 优化表格配置，避免不必要的重新计算
  const table = useReactTable({
    data,
    columns,
    state: {
      sorting,
      columnVisibility,
      rowSelection,
      columnFilters,
      pagination,
    },
    manualPagination: true,
    onPaginationChange: setPagination,
    rowCount: rowCount,
    // 添加安全的行ID获取方法，防止undefined或null值导致的错误
    getRowId: row => {
      if (row.id === undefined || row.id === null) {
        // 行数据缺少ID，使用更安全的随机ID生成方法
        return `row-${Math.random().toString(36).substring(2, 11)}-${Date.now().toString(36)}`;
      }
      return row.id.toString();
    },
    enableRowSelection: true,
    autoResetPageIndex: false, //turn off auto reset of pageIndex
    onRowSelectionChange: setRowSelection,
    onSortingChange: setSorting,
    onColumnFiltersChange: setColumnFilters,
    onColumnVisibilityChange: setColumnVisibility,
    getCoreRowModel: getCoreRowModel(),
    getFilteredRowModel: getFilteredRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
    getSortedRowModel: getSortedRowModel(),
    getFacetedRowModel: getFacetedRowModel(),
    getFacetedUniqueValues: getFacetedUniqueValues(),
  })

  return (
    <div className='space-y-4'>
      <DataTableToolbar table={table} />
      <div className='overflow-hidden rounded-md border'>
        <Table>
          <TableHeader>
            {table.getHeaderGroups().map((headerGroup) => (
              <TableRow key={headerGroup.id} className='group/row'>
                {headerGroup.headers.map((header) => {
                  return (
                    <TableHead
                      key={header.id}
                      colSpan={header.colSpan}
                      className={header.column.columnDef.meta?.className ?? ''}
                    >
                      {header.isPlaceholder
                        ? null
                        : flexRender(
                          header.column.columnDef.header,
                          header.getContext()
                        )}
                    </TableHead>
                  )
                })}
              </TableRow>
            ))}
          </TableHeader>
          <TableBody>
            {isLoading ? (
              // 加载状态显示
              <TableRow>
                <TableCell
                  colSpan={columns.length}
                  className='h-24 text-center'
                >
                  <div className="flex flex-col justify-center items-center" role="status" aria-live="polite">
                    <svg className="animate-spin h-8 w-8 mb-2" viewBox="0 0 24 24" aria-hidden="true">
                      <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                      <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                    </svg>
                    <p className="text-sm text-gray-500">Loading user data...</p>
                  </div>
                </TableCell>
              </TableRow>
            ) : isError ? (
              // 错误状态显示
              <TableRow>
                <TableCell
                  colSpan={columns.length}
                  className='h-24 text-center text-red-500'
                >
                  <div className="flex flex-col items-center justify-center gap-2" role="alert" aria-live="assertive">
                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                      <circle cx="12" cy="12" r="10" />
                      <line x1="12" y1="8" x2="12" y2="12" />
                      <line x1="12" y1="16" x2="12.01" y2="16" />
                    </svg>
                    <p>Error loading data: {error instanceof Error ? error.message : 'Unknown error'}</p>
                    <div className="flex gap-2 mt-2">
                      <button
                        onClick={() => refetch()}
                        className="px-4 py-2 text-sm bg-blue-100 text-blue-700 rounded hover:bg-blue-200"
                      >
                        Retry
                      </button>
                      <button
                        onClick={() => {
                          setPagination(prev => ({ ...prev, pageIndex: 0 }));
                          setTimeout(() => refetch(), 0);
                        }}
                        className="px-4 py-2 text-sm bg-red-100 text-red-700 rounded hover:bg-red-200"
                      >
                        Reset & Retry
                      </button>
                    </div>
                  </div>
                </TableCell>
              </TableRow>
            ) : table.getRowModel().rows?.length ? (
              table.getRowModel().rows.map((row) => (
                <TableRow
                  key={row.id}
                  data-state={row.getIsSelected() ? 'selected' : undefined}
                  className='group/row'
                >
                  {row.getVisibleCells().map((cell) => (
                    <TableCell
                      key={cell.id}
                      className={cell.column.columnDef.meta?.className ?? ''}
                    >
                      {flexRender(
                        cell.column.columnDef.cell,
                        cell.getContext()
                      )}
                    </TableCell>
                  ))}
                </TableRow>
              ))
            ) : (
              <TableRow>
                <TableCell
                  colSpan={columns.length}
                  className='h-24 text-center'
                >
                  <div className="flex flex-col items-center justify-center gap-2" role="status" aria-live="polite">
                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                      <circle cx="12" cy="12" r="10" />
                      <line x1="8" y1="12" x2="16" y2="12" />
                    </svg>
                    <p className="text-gray-500">No users found matching your criteria.</p>
                  </div>
                </TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </div>
      <DataTablePagination table={table} />
    </div>
  )
}
